package com.yuanqi.controller;

import com.yuanqi.domain.AccountsPayable;
import com.yuanqi.repository.AccountsPayableRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/finance/accounts-payable")
@CrossOrigin(origins = "*")
public class AccountsPayableController {
    
    @Autowired
    private AccountsPayableRepository accountsPayableRepository;
    
    @GetMapping
    public ResponseEntity<List<AccountsPayable>> getAllAccountsPayable() {
        List<AccountsPayable> accountsPayable = accountsPayableRepository.findAll();
        return ResponseEntity.ok(accountsPayable);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<AccountsPayable> getAccountsPayableById(@PathVariable Long id) {
        return accountsPayableRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping("/supplier/{supplierId}")
    public ResponseEntity<List<AccountsPayable>> getAccountsPayableBySupplier(@PathVariable Long supplierId) {
        List<AccountsPayable> accountsPayable = accountsPayableRepository.findBySupplierId(supplierId);
        return ResponseEntity.ok(accountsPayable);
    }
    
    @GetMapping("/overdue")
    public ResponseEntity<List<AccountsPayable>> getOverdueAccountsPayable() {
        List<AccountsPayable> overdueAccounts = accountsPayableRepository.findByOverdueStatus(1);
        return ResponseEntity.ok(overdueAccounts);
    }
    
    @PostMapping
    public ResponseEntity<AccountsPayable> createAccountsPayable(@RequestBody AccountsPayable accountsPayable) {
        accountsPayable.setCreateTime(LocalDateTime.now());
        AccountsPayable saved = accountsPayableRepository.save(accountsPayable);
        return ResponseEntity.ok(saved);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<AccountsPayable> updateAccountsPayable(@PathVariable Long id, @RequestBody AccountsPayable accountsPayableDetails) {
        return accountsPayableRepository.findById(id)
                .map(existing -> {
                    existing.setSupplierId(accountsPayableDetails.getSupplierId());
                    existing.setPoId(accountsPayableDetails.getPoId());
                    existing.setPayableAmount(accountsPayableDetails.getPayableAmount());
                    existing.setPaidAmount(accountsPayableDetails.getPaidAmount());
                    existing.setUnpaidAmount(accountsPayableDetails.getUnpaidAmount());
                    existing.setDueDate(accountsPayableDetails.getDueDate());
                    existing.setOverdueStatus(accountsPayableDetails.getOverdueStatus());
                    
                    // 检查是否逾期
                    if (LocalDate.now().isAfter(existing.getDueDate()) && existing.getUnpaidAmount().doubleValue() > 0) {
                        existing.setOverdueStatus(1);
                    } else {
                        existing.setOverdueStatus(0);
                    }
                    
                    return ResponseEntity.ok(accountsPayableRepository.save(existing));
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteAccountsPayable(@PathVariable Long id) {
        if (accountsPayableRepository.existsById(id)) {
            accountsPayableRepository.deleteById(id);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }
    
    @GetMapping("/stats/total-overdue")
    public ResponseEntity<Double> getTotalOverdueAmount() {
        Double totalOverdue = accountsPayableRepository.getTotalOverdueAmount();
        return ResponseEntity.ok(totalOverdue != null ? totalOverdue : 0.0);
    }
    
    @GetMapping("/stats/total-unpaid")
    public ResponseEntity<Double> getTotalUnpaidAmount() {
        Double totalUnpaid = accountsPayableRepository.getTotalUnpaidAmount();
        return ResponseEntity.ok(totalUnpaid != null ? totalUnpaid : 0.0);
    }
}


